/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.basic.hazard.sds.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.basic.hazard.sds.dto.HazChemicalOutDTO;
import com.hopes.bizz.basic.hazard.sds.dto.HazChemicalOutExcelDTO;
import com.hopes.bizz.basic.hazard.sds.entity.HazChemicalOutEntity;
import com.hopes.bizz.basic.hazard.sds.entity.HazChemicalSdsEntity;
import com.hopes.bizz.basic.hazard.sds.service.HazChemicalOutService;
import com.hopes.bizz.basic.hazard.sds.service.HazChemicalSdsService;
import com.hopes.bizz.basic.hazard.sds.vo.HazChemicalOutExcelVO;
import com.hopes.bizz.basic.hazard.support.HazChemicalSupport;
import com.hopes.bizz.common.core.util.DateUtils;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.excel.annotation.RequestExcel;
import com.hopes.boss.common.excel.annotation.ResponseExcel;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 危化品出库记录
 *
 * @author daijie
 * @date 2023-11-13 19:29:15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/out")
@Tag(description = "out", name = "危化品出库记录管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class HazChemicalOutController {

    private final HazChemicalOutService hazChemicalOutService;
    private final HazChemicalSupport hazChemicalSupport;
    private final HazChemicalSdsService hazChemicalSdsService;

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param hazChemicalOut 危化品出库记录
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('haz_out_view')")
    public R gethazChemicalOutPage(Page page, HazChemicalOutDTO hazChemicalOut) {
        LambdaQueryWrapper<HazChemicalOutEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalOut.getChemicalId()), HazChemicalOutEntity::getChemicalId, hazChemicalOut.getChemicalId());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalOut.getOrgId()), HazChemicalOutEntity::getOrgId, hazChemicalOut.getOrgId());

        wrapper.eq(ObjectUtils.isNotNull(hazChemicalOut.getOutStorageType()), HazChemicalOutEntity::getOutStorageType, hazChemicalOut.getOutStorageType());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalOut.getStorageLocationId()), HazChemicalOutEntity::getStorageLocationId, hazChemicalOut.getStorageLocationId());

        wrapper.ge(ObjectUtil.isNotNull(hazChemicalOut.getBeginTime()), HazChemicalOutEntity::getOutDate, hazChemicalOut.getBeginTime());
        wrapper.le(ObjectUtil.isNotNull(hazChemicalOut.getEndTime()), HazChemicalOutEntity::getOutDate, hazChemicalOut.getEndTime());

        if (ObjectUtils.isNotNull(hazChemicalOut.getSdsCode())) {
            String sdsCode = hazChemicalOut.getSdsCode();
            List<Long> sdsIdList = hazChemicalSdsService.list(Wrappers.lambdaQuery(HazChemicalSdsEntity.class)
                            .like(HazChemicalSdsEntity::getName, sdsCode).or()
                            .like(HazChemicalSdsEntity::getSdsCode, sdsCode).or()
                            .like(HazChemicalSdsEntity::getCasNo, sdsCode))
                    .stream().map(HazChemicalSdsEntity::getId).collect(Collectors.toList());
            if (sdsIdList.isEmpty()) {
                return R.ok(Collections.emptyList());
            }
            wrapper.in(HazChemicalOutEntity::getChemicalId, sdsIdList);
        }
        wrapper.orderByDesc(HazChemicalOutEntity::getOutDate);
        return R.ok(hazChemicalOutService.page(page, wrapper));
    }


    /**
     * 通过id查询危化品出库记录
     *
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('haz_out_view')")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(hazChemicalOutService.getById(id));
    }

    /**
     * 新增危化品出库记录
     *
     * @param hazChemicalOut 危化品出库记录
     * @return R
     */
    @Operation(summary = "新增危化品出库记录", description = "新增危化品出库记录")
    @SysLog("新增危化品出库记录")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('haz_out_add')")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody HazChemicalOutEntity hazChemicalOut) {
        hazChemicalOut.setOutDate(DateUtils.dateLimitDay(hazChemicalOut.getOutDate()));
        hazChemicalOutService.save(hazChemicalOut);
        hazChemicalSupport.calculateStock(hazChemicalOut.getChemicalId());
        hazChemicalSupport.calculateStockHis(hazChemicalOut.getChemicalId(), hazChemicalOut.getOutDate());
        return R.ok();
    }

    /**
     * 修改危化品出库记录
     *
     * @param hazChemicalOut 危化品出库记录
     * @return R
     */
    @Operation(summary = "修改危化品出库记录", description = "修改危化品出库记录")
    @SysLog("修改危化品出库记录")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('haz_out_edit')")
    @Transactional(rollbackFor = Exception.class)
    public R updateById(@RequestBody HazChemicalOutEntity hazChemicalOut) {
        hazChemicalOut.setOutDate(DateUtils.dateLimitDay(hazChemicalOut.getOutDate()));
        hazChemicalOutService.updateById(hazChemicalOut);
        hazChemicalSupport.calculateStock(hazChemicalOut.getChemicalId());
        hazChemicalSupport.calculateStockHis(hazChemicalOut.getChemicalId(), hazChemicalOut.getOutDate());
        return R.ok();
    }

    /**
     * 通过id删除危化品出库记录
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除危化品出库记录", description = "通过id删除危化品出库记录")
    @SysLog("通过id删除危化品出库记录")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('haz_out_del')")
    @Transactional(rollbackFor = Exception.class)
    public R removeById(@RequestBody Long[] ids) {
        for (Long id : ids) {
            HazChemicalOutEntity entity = hazChemicalOutService.getById(id);
            hazChemicalOutService.removeById(id);
            hazChemicalSupport.calculateStock(entity.getChemicalId());
            hazChemicalSupport.calculateStockHis(entity.getChemicalId(), entity.getOutDate());
        }
        return R.ok();
    }

    /**
     * excel模板
     *
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/template")
    @PreAuthorize("@pms.hasPermission('haz_out_export')")
    public List<HazChemicalOutExcelVO> template() {
        return hazChemicalOutService.exportExcel(Arrays.asList(new HazChemicalOutEntity()));
    }

    /**
     * 导出excel 表格
     *
     * @param hazChemicalOut 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('haz_out_export')")
    public List<HazChemicalOutExcelVO> export(HazChemicalOutDTO hazChemicalOut) {
        LambdaQueryWrapper<HazChemicalOutEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalOut.getChemicalId()), HazChemicalOutEntity::getChemicalId, hazChemicalOut.getChemicalId());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalOut.getOutStorageType()), HazChemicalOutEntity::getOutStorageType, hazChemicalOut.getOutStorageType());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalOut.getStorageLocationId()), HazChemicalOutEntity::getStorageLocationId, hazChemicalOut.getStorageLocationId());
        wrapper.ge(ObjectUtil.isNotNull(hazChemicalOut.getBeginTime()), HazChemicalOutEntity::getOutDate, hazChemicalOut.getBeginTime());
        wrapper.le(ObjectUtil.isNotNull(hazChemicalOut.getEndTime()), HazChemicalOutEntity::getOutDate, hazChemicalOut.getEndTime());

        return hazChemicalOutService.exportExcel(hazChemicalOutService.list(wrapper));
    }

    /**
     * 导入excel 表格
     *
     * @param hazChemicalOutExcelDtoList 查询条件
     * @param bindingResult              错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('haz_out_export')")
    public R importExcel(@RequestExcel List<HazChemicalOutExcelDTO> hazChemicalOutExcelDtoList, BindingResult bindingResult) {
        return hazChemicalOutService.importExcel(hazChemicalOutExcelDtoList, bindingResult);
    }
}
